package org.testmyapp;

import java.io.IOException;
import java.io.PrintWriter;

import javax.inject.Inject;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.activiti.engine.IdentityService;
import org.activiti.engine.identity.User;
import org.testmyapp.engine.EngineProvider;
import org.testmyapp.session.SessionForUser;

public class LoginServlet extends HttpServlet implements Servlet {

	@Inject
	private IdentityService identityService;

	@Inject
	private SessionForUser sessionUser;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		resp.setContentType("text/html");
		PrintWriter writer = resp.getWriter();
		writer.println("<center><h1>LOGIN</h1><br>");
		writer.println("<form method=\"post\" action=\"LoginServlet\">");
		writer.println("<table>");
		writer.println("<tr bgcolor=\"#677BBC\">");
		writer.println("<td><b>ID</b></td><td><input type=\"text\" name=\"id\"></td>");
		writer.println("</tr>");
		writer.println("<tr bgcolor=\"#677BBC\">");
		writer.println("<td><b>PASSWORD</b></td><td><input type=\"password\" name=\"password\"></td>");
		writer.println("</tr>");
		writer.println("<tr bgcolor=\"#677BBC\">");
		writer.println("<td colspan=2><input type=\"submit\" value=\"login\" name=\"login_submit\"></td>");
		writer.println("</tr>");
		writer.println("</table></center>");
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		resp.setContentType("text/html");
		PrintWriter writer = resp.getWriter();
		String id = req.getParameter("id");
		String password = req.getParameter("password");
		String submit = req.getParameter("login_submit");
		if (submit != null && submit.equals("login")) {
			User singleResult = identityService.createUserQuery().userId(id)
					.singleResult();
			if (singleResult != null) {
				if (password.equals(singleResult.getPassword())) {
					writer.println("<h1><font color=\"green\">LOGGED IN AS USER "
							+ id + "</font></h1>");
					sessionUser.setUser(id);
					req.getRequestDispatcher("Overview").forward(req, resp);
				}
			} else {
				writer.println("<h1><font color=\"red\">NO USER WITH ID " + id
						+ "</font></h1>");
			}
		} else {
			doGet(req, resp);
		}
	}

}
